package org.shilong.UI.friend;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.shilong.Loader.ImageLoader;
import org.shilong.MContext.WebRequest.WebRequestContext;
import org.shilong.Model.BusinessCardModel;
import org.shilong.Model.FriendModel;
import org.shilong.UI.R;
import org.shilong.Utility.constants.APIConstants;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class ShowFriendDetailFrame extends Activity {

	private String image_url, weibo_id;

	private ListView friend_detail_listview;

	private Button to_query_his_bc_button;

	private ImageView show_detail_header_imageview;

	private ProgressDialog dialog;

	private static List<FriendModel> detailList = new ArrayList<FriendModel>();

	private LinearLayout show_detail_friend_mother_layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.new_layout_show_friend_detail_content);

		Intent it = getIntent();

		Bundle bun = it.getExtras();

		image_url = bun.getString("image_url");
		weibo_id = bun.getString("weibo_id");

		dialog = new ProgressDialog(this);

		dialog.setMessage("获取的ta的微博好友中..");

		initViews();

		registerEvents();
	}

	private void showDialog() {

		dialog.show();
	}

	private void cannelDialog() {

		dialog.dismiss();
	}

	private void registerEvents() {
		// TODO Auto-generated method stub

		to_query_his_bc_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				showBusinessCard(weibo_id);
			}
		});
	}

	private void initViews() {

		show_detail_friend_mother_layout = (LinearLayout) this
				.findViewById(R.id.show_detail_friend_mother_layout);

		show_detail_header_imageview = (ImageView) this
				.findViewById(R.id.show_detail_header_imageview);

		to_query_his_bc_button = (Button) this
				.findViewById(R.id.to_query_his_bc_button);

		friend_detail_listview = (ListView) this
				.findViewById(R.id.friend_detail_listview);

		ImageLoader imgIoader = new ImageLoader();

		Drawable draw = imgIoader.loadImage(image_url,
				new ImageLoader.ImageCallBack() {

					@Override
					public void setImageDrawable(Drawable imageDrawable) {
						// TODO Auto-generated method stub
						show_detail_header_imageview
								.setImageDrawable(imageDrawable);
					}
				});

		if (draw != null) {

			show_detail_header_imageview.setImageDrawable(draw);
		}

		/*
		 * NewFriendDetailListViewLoader loader = new
		 * NewFriendDetailListViewLoader(friend_detail_listview, this,
		 * weibo_id); loader.startLoader();
		 */

		GetFriJob task = new GetFriJob(friend_detail_listview, weibo_id);

		task.execute();

	}

	private void setAdapter() {

		System.out.println("加载迭代器");

		friend_detail_listview.setAdapter(new MyAdapter());

	}

	private PopupWindow myPopWindow;

	private void showBusinessCard(String w_id) {

		List<BusinessCardModel> ll = new ArrayList<BusinessCardModel>();

		String rlt = "";
		rlt = WebRequestContext.createInstance(
				WebRequestContext.TYPE_QUERY_BusinessCard_BY_ID)
				.getWebRequestRlt(w_id);
		try {
			ll = getList(rlt);

			if (ll == null || ll.size() == 0) {

				Toast.makeText(ShowFriendDetailFrame.this, "暂无他的名片",
						Toast.LENGTH_LONG).show();

			} else {

				myPopWindow = new PopupWindow(this);

				myPopWindow.setFocusable(true);
				myPopWindow.setOutsideTouchable(true);
				myPopWindow.setTouchable(true);

				LayoutInflater inlater = (LayoutInflater) ShowFriendDetailFrame.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				View root = inlater.inflate(
						R.layout.layout_popwindow_show_bc_content, null);

				myPopWindow.setBackgroundDrawable(ShowFriendDetailFrame.this
						.getResources().getDrawable(R.drawable.body_bg_img));

				int width = show_detail_friend_mother_layout.getWidth();
				int height = show_detail_friend_mother_layout.getHeight();
				myPopWindow.setWidth(width - 20);
				myPopWindow.setHeight(height);

				myPopWindow.setAnimationStyle(R.style.MyPopWindow);

				myPopWindow.setContentView(root);

				myPopWindow.showAtLocation(show_detail_friend_mother_layout,
						Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

				myPopWindow.setTouchInterceptor(new View.OnTouchListener() {

					@Override
					public boolean onTouch(View arg0, MotionEvent event) {
						// TODO Auto-generated method stub

						if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {

							myPopWindow.dismiss();
							return true;
						}
						return false;
					}
				});

				BusinessCardModel model = ll.get(0);

				TextView show_tele_textview = (TextView) root
						.findViewById(R.id.show_tele_num_textview);
				TextView show_com_name_textview = (TextView) root
						.findViewById(R.id.show_com_name_textview);
				TextView show_business_textivew = (TextView) root
						.findViewById(R.id.show_business_textview);
				TextView show_domain_textview = (TextView) root
						.findViewById(R.id.show_domain_textview);
				TextView show_sex_textview = (TextView) root
						.findViewById(R.id.show_sex_textview);
				TextView show_age_textview = (TextView) root
						.findViewById(R.id.show_age_textview);

				show_tele_textview.setText(Html.fromHtml("<u>"
						+ model.getTelephone_number() + "</u>"));
				show_com_name_textview.setText(Html.fromHtml("<u>"
						+ model.getCompany_name() + "</u>"));
				show_business_textivew.setText(Html.fromHtml("<u>"
						+ model.getBussiness() + "</u>"));
				show_domain_textview.setText(Html.fromHtml("<u>"
						+ model.getDomain() + "</u>"));
				show_age_textview.setText(Html.fromHtml("<u>" + model.getAge()
						+ "</u>"));
				show_sex_textview.setText(Html.fromHtml("<u>" + model.getSex()
						+ "</u>"));
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private List<BusinessCardModel> getList(String rlt) throws JSONException {

		List<BusinessCardModel> list = new ArrayList<BusinessCardModel>();

		JSONObject obj = new JSONObject(rlt);

		JSONArray arr = obj.getJSONArray("rlt");

		for (int i = 0; i < arr.length(); i++) {

			BusinessCardModel model = new BusinessCardModel();

			JSONObject oo = arr.getJSONObject(i);

			model.setAge(oo.getString("age"));
			model.setBussiness(oo.getString("bussiness"));
			model.setCompany_name(oo.getString("company_name"));
			model.setDomain(oo.getString("domain"));
			model.setSex(oo.getString("sex"));
			model.setTelephone_number(oo.getString("telephone_number"));

			list.add(model);
		}

		return list;
	}

	/**
	 * 获取好友id的列表
	 * 
	 * @param rlt
	 * @return
	 * @throws JSONException 
	 */
	private List<FriendModel> getFriendList(String rlt) throws JSONException {

		List<FriendModel> friList = new ArrayList<FriendModel>();

		JSONObject obj = new JSONObject(rlt);
		JSONArray arr = obj.getJSONArray( "users" );
		
		for( int i  = 0; i < arr.length(); i++ ){
			
			JSONObject oo = arr.getJSONObject(i);
			
			FriendModel model = new FriendModel();
			
			model.setDescription(oo.getString("description") );
			model.setLocation(oo.getString("location"));
			model.setProfile_image_url(oo.getString("profile_image_url"));
			model.setScreen_name( oo.getString("screen_name") );
			model.setWeibo_id( oo.getString("id") );
			
			friList.add(model);
			
		}
		return friList;

	}

	private class MyAdapter extends BaseAdapter {

		public MyAdapter() {

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return detailList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return detailList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub

			final FriendModel model = detailList.get(arg0);

			LayoutInflater inflater = (LayoutInflater) ShowFriendDetailFrame.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View root = inflater.inflate(
					R.layout.inner_friend_listview_item_layout, null);

			/**
			 * 初始化头像
			 */
			final ImageView iv = (ImageView) root
					.findViewById(R.id.inner_show_header_img_imageview);

			ImageLoader loader = new ImageLoader();

			Drawable draw = loader.loadImage(model.getProfile_image_url(),
					new ImageLoader.ImageCallBack() {

						@Override
						public void setImageDrawable(Drawable imageDrawable) {
							// TODO Auto-generated method stub

							iv.setImageDrawable(imageDrawable);
						}
					});

			if (draw != null)
				iv.setImageDrawable(draw);

			TextView inner_friend_screen_name_textview = (TextView) root
					.findViewById(R.id.inner_friend_screen_name_textview);
			TextView inner_friend_location_textview = (TextView) root
					.findViewById(R.id.inner_friend_location_textview);
			TextView inner_friend_desc_textview = (TextView) root
					.findViewById(R.id.inner_friend_desc_textview);

			inner_friend_screen_name_textview.setText(model.getScreen_name());
			inner_friend_location_textview.setText(model.getLocation());
			inner_friend_desc_textview.setText(model.getDescription());

			return root;

		}
	}

	private class GetFriJob extends AsyncTask<String, String, String> {

		private ListView lv;

		private String w_id;

		public GetFriJob(ListView ll, String w_id) {

			this.w_id = w_id;

			this.lv = ll;

		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			System.out.println("他/她的微博id是:" + w_id);
			
			System.out.println("启动task了");

			Utility.setAuthorization(new Oauth2AccessTokenHeader());

			WeiboParameters wp = new WeiboParameters();
			
			wp.add( "uid", weibo_id );
			
			List<FriendModel> list = new ArrayList<FriendModel>();
			//获取互粉好友
			String friendsRlt = "";
			try {
				friendsRlt = Weibo.getInstance().request(ShowFriendDetailFrame.this, APIConstants.GET_FRIEND_DIRECTLY,
						wp, Utility.HTTPMETHOD_GET,
						Weibo.getInstance().getAccessToken());
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("获取互粉好用信息的是"+ friendsRlt );
			
			try {
				list = getFriendList( friendsRlt );
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			ShowFriendDetailFrame.detailList = list;
			
			
			friend_detail_listview.post(  new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					friend_detail_listview.setAdapter( new MyAdapter());
					
				}
			});
			detailList.size();
			
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			// setAdapter();
			cannelDialog();

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub

			showDialog();

			super.onPreExecute();

		}

	}
	
	

}
